package com.jwgf.smarowindingmachine_unity.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.google.android.material.textfield.TextInputLayout;
import com.jwgf.adapter.DensityUtils;
import com.jwgf.adapter.MultiItemTypeAdapter;
import com.jwgf.decoration.SpaceItemDecoration;
import com.jwgf.itemviewdelegates.CraftSelectAttr;
import com.jwgf.itemviewdelegates.CraftSelectDelegate;
import com.jwgf.objectbox.ObjectBox;
import com.jwgf.objectbox.SpindleParameter;
import com.jwgf.objectbox.SpindleParameter_;
import com.jwgf.smarowindingmachine_unity.R;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;

public class CraftImportDialog extends DialogFragment {
    public static final String CRAFT_PATH = "craft_path";
    private TextInputLayout name;
    private RecyclerView rv;
    private MultiItemTypeAdapter<Object> rvAdapter;
    private List<SpindleParameter> importCrafts = new ArrayList<>();
    private List<SpindleParameter> parameters;
    private Box<SpindleParameter> box = ObjectBox.get().boxFor(SpindleParameter.class);
    private Runnable callback;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.craft_export_view, null);
        name = v.findViewById(R.id.craft_name);
        name.setVisibility(View.GONE);
        rv = v.findViewById(R.id.craft_recycler);
        final List list = new ArrayList();
        Bundle args = getArguments();
        File craftFile = new File(args.getString(CRAFT_PATH));
        String fileName = craftFile.getName();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (suffix.equals("cra")) {
            try {
                FileReader reader = new FileReader(craftFile);
                char[] buffer = new char[(int) craftFile.length()];
                reader.read(buffer);
                reader.close();
                String craft = new String(buffer);
                parameters = JSONArray.parseArray(craft, SpindleParameter.class);
                for (SpindleParameter parameter : parameters) {
                    CraftSelectAttr attr = new CraftSelectAttr();
                    attr.setCraftName(parameter.craftName);
                    attr.setId(parameter.id);
                    list.add(attr);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getContext(), "请选择.cra文件！", Toast.LENGTH_LONG).show();
            dismiss();
        }
        rvAdapter = new MultiItemTypeAdapter<Object>(getContext(), list);
        rvAdapter.addItemViewDelegate(new CraftSelectDelegate());
        rvAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position == -1)
                    return;
                CraftSelectAttr attr = ((CraftSelectAttr) rvAdapter.getDatas().get(position));
                if (attr.isSelected()) {
                    attr.setSelected(false);
                    importCrafts.remove(parameters.get(position));
                } else {
                    SpindleParameter para = box.query()
                            .equal(SpindleParameter_.craftName, attr.getCraftName()).build().findFirst();
                    if (para != null) {
                        Toast.makeText(getContext(), attr.getCraftName() + "已存在！", Toast.LENGTH_LONG).show();
                    } else {
                        attr.setSelected(true);
                        importCrafts.add(parameters.get(position));
                    }

                }
                rvAdapter.notifyDataSetChanged();

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
        rv.setLayoutManager(layoutManager);
        rv.addItemDecoration(new SpaceItemDecoration(DensityUtils.dp2px(2), DensityUtils.dp2px(2)));
        rv.setAdapter(rvAdapter);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("批次导入");
        builder.setView(v);
        builder.setPositiveButton("导入", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Box<SpindleParameter> box = ObjectBox.get().boxFor(SpindleParameter.class);
                // 清除导入配方的id
                for (SpindleParameter parameter: importCrafts) {
                    parameter.id = 0;
                }
                box.put(importCrafts);
                if (callback != null) {
                    callback.run();
                }
            }
        });

        return builder.create();
    }

    public void setCallback(Runnable callback) {
        this.callback = callback;
    }
}
